<template>
  <a-row :gutter="24">
    <!--    <a-col :md="3" :sm="24">-->
    <!--      <div class="dipPic"></div>-->
    <!--      <div class="dipClass">-->
    <!--        <li><span class="dipTip">倾角X轴</span> <span class="dipNum">{{ this.dip[0] }}</span></li>-->
    <!--        <li><span class="dipTip">倾角Y轴</span> <span class="dipNum">{{ this.dip[1] }}</span></li>-->
    <!--        <li><span class="dipTip">倾角Z轴</span> <span class="dipNum">{{ this.dip[2] }}</span></li>-->
    <!--      </div>-->
    <!--    </a-col>-->
    <a-col :md="4" :sm="24">
      <a-card :bordered="false" :loading="treeLoading">
        <a-directory-tree
          :showIcon="false"
          :treeData="treeList"
          v-if="treeList.length"
          @select="handleClick"
          :defaultExpandAll="true"
          :replaceFields="replaceFields" />
      </a-card>
    </a-col>
    <a-col :md="19" :sm="24">
      <a-card :bordered="false">
        <a-tabs default-active-key="1" tabPosition="left" @change="change" size="large">
          <a-tab-pane tab="数据" key="1">
            <div class="table-page-search-wrapper">
              <a-form layout="inline">
                <a-row :gutter="0">
                  <a-col :md="6" :sm="24">
                    <a-form-item label="网关名称">
                      <a-select style="width: 100%" v-model="queryParam.gatewayId" allow-clear placeholder="请选择网关名称" >
                        <a-select-option v-for="(item,ind) in gatewayList" :key="ind" :value="item.id" >{{ item.gatewayName }}</a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>

                  <a-col :md="!advanced && 6 || 24" :sm="24">
                    <span
                      class="table-page-search-submitButtons"
                      style="padding-left: 16px;"
                      :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                      <a-button type="primary" class="btn_search_reset" @click="refresh()"><a-icon
                        type="search"/>查询</a-button>
                    </span>
                  </a-col>
                </a-row>
              </a-form>
            </div>

            <s-table
              ref="table"
              size="middle"
              :columns="columns"
              :data="loadData"
              :alert="true"
              :rowKey="(record) => record.id"
            >
              <span slot="dipx" slot-scope="text, record">
                {{ record.dip.split(",")[0] }}
              </span>
              <span slot="dipy" slot-scope="text, record">
                {{ record.dip.split(",")[1] }}
              </span>
              <span slot="dipz" slot-scope="text, record">
                {{ record.dip.split(",")[2] }}
              </span>
              <span slot="action" slot-scope="text, record">
                <a-popconfirm placement="topRight" class="btn_del" title="确认删除？" @confirm="() => del(record)">
                  <a>删除</a>
                </a-popconfirm>
              </span>
            </s-table>
          </a-tab-pane>
          <a-tab-pane tab="图表" loading="true" key="2">
            <div class="chart" ref="ccc" style="width:95vh;height:60vh"></div>
          </a-tab-pane>
        </a-tabs>

        <add-form ref="addForm" @ok="handleOk"/>
        <edit-form ref="editForm" @ok="handleOk"/>

      </a-card>
    </a-col>
  </a-row>

</template>

<script>
  import { STable } from '@/components'
  import {
    page,
    del,
    getNewOne,
    getDipUploadFrequency
  } from '@/api/modular/main/wpuploadlog/wpUploadLogManage'
  import { treeList } from '@/api/modular/main/bizstation/bizStationManage'
  import addForm from './addForm'
  import editForm from './editForm'
  import * as echarts from 'echarts'
  import { gatewayList } from '@/api/modular/main/bizgateway/bizGatewayManage'

  export default {
    components: {
      STable,
      addForm,
      editForm
    },

    data () {
      return {
        advanced: false, // 高级搜索 展开/关闭
        queryParam: {}, // 查询参数
        columns: [ // 表头
          {
            title: '倾角x',
            dataIndex: 'dipx',
            scopedSlots: { customRender: 'dipx' }
          },
          {
            title: '倾角y',
            dataIndex: 'dipy',
            scopedSlots: { customRender: 'dipy' }
          }, {
            title: '倾角z',
            dataIndex: 'dipz',
            scopedSlots: { customRender: 'dipz' }
          },
          {
            title: '时间',
            dataIndex: 'createTime'
          },
          /* {
            title: '通道ID',
            dataIndex: 'channelId'
          }, */
          {
            title: '网关编号',
            dataIndex: 'gatewayCode'
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: '150px',
            scopedSlots: { customRender: 'action' }
          }
        ],
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          return page(Object.assign(parameter, this.queryParam)).then((res) => {
            return res.data
          })
        },
        timerIntevalId: '',
        selectedRowKeys: [],
        selectedRows: [],
        defaultExpandedKeys: [],
        replaceFields: {
          key: 'id'
        },
        dip: [],
        chart: '',
        chartData: [],
        changeChart: true,
        showRentPrise: false,
        times: 3000,
        treeList: [],
        treeLoading: true,
        gatewayList: []
      }
    },

    methods: {
      change (key) {
        if (key === 1) {
          this.changeChart = false
          this.showRentPrise = true
        } else {
          this.changeChart = true
          this.showRentPrise = false
          this.initchart()
        }
      },
      handleClick (e) {
        this.queryParam = {}
        const param = {
          stationId: e.toString()
        }
        this.queryParam.gatewayIds = ''
        gatewayList(param).then(res => {
          this.gatewayIds = []
          this.gatewayList = res.data
          for (let i = 0; i < res.data.length; i++) {
            this.gatewayIds.push(res.data[i].id)
          }
          this.queryParam.gatewayIds = this.gatewayIds.toString()
          this.$refs.table.refresh()
        })
      },
      initchart () {
        const newPromise = new Promise((resolve) => {
          resolve()
        })
        newPromise.then(() => {
          const nowChart = this.$refs.ccc
          this.chart = echarts.init(nowChart)
          var parameter = {
            pageSize: '100',
            pageNo: '1'
          }
          page(parameter).then((res) => {
            res.data.rows = res.data.rows.reverse()
            const rows = res.data
            this.chartData = rows
            this.updateChart()
          })
        })
      },
      refresh(){
        this.$refs.table.refresh()

      },
      updateChart () {
        var xData = []
        var yData = []
        var time = []
        const rows = this.chartData.rows
        for (let i = 0; i < rows.length; i++) {
          const allData = (rows[i].dip || '').split(',')
          xData.push(allData[0])
          yData.push(allData[1])
          time.push(rows[i].createTime)
        }
        var option = {
          tooltip: {
            trigger: 'axis',
            formatter: function (value) {
              let str = ''
              str = str + '<span>时间:</span>' + '<span>' + value[0].axisValue + '</span></br>'
              str = str + '<span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:#66ffff;"></span>' + '<span style="margin-right:6px">X轴:</span>' + '<span style="float:right">' + value[0].value + '</span></br>'
              str = str + '<span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:#ffff99;"></span>' + '<span style="margin-right:6px">Y轴:</span>' + '<span style="float:right">' + value[1].value + '</span></br>'
              return str
            }
          },
          legend: {
            data: [{ name: 'X轴', textStyle: { color: 'white' } }, { name: 'Y轴', textStyle: { color: 'white' } }]
          },
          grid: {
            top: 30,
            left: 60,
            right: 30,
            bottom: 40
          },
          xAxis: [
            {
              show: true,
              data: time,
              type: 'category',
              boundaryGap: false,
              axisLine: {
                show: false,
                lineStyle: {
                  color: '#fff',
                  width: 1
                }
              },
              // 竖线
              splitLine: {
                show: true,
                lineStyle: {
                  color: ['#315070']
                }
              }
            }
          ],
          yAxis: [
            {
              show: true,
              type: 'value',
              lineStyle: {
                show: false,
                color: '#fff'
              },
              // 横线
              splitLine: {
                show: true,
                lineStyle: {
                  color: ['#315070']
                }
              },
              axisLine: {
                lineStyle: {
                  show: true,
                  color: '#fff',
                  width: 1
                }
              }
            }
          ],
          series: [
            {
              name: 'X轴',
              type: 'line',
              data: xData,
              symbolSize: 0,
              lineStyle: {
                color: '#66ffff'
              }
            },
            {
              name: 'Y轴',
              type: 'line',
              data: yData,
              symbolSize: 0,
              lineStyle: {
                color: '#ffff99'
              }
            }
          ]
        }
        this.chart.setOption(option)
      },
      del (record) {
        del(record).then((res) => {
          if (res.success) {
            this.$message.success('删除成功')
            this.$refs.table.refresh()
          } else {
            this.$message.error('删除失败：' + res.message)
          }
        }).catch((err) => {
          this.$message.error('删除错误：' + err.message)
        })
      },
      toggleAdvanced () {
        this.advanced = !this.advanced
      },
      handleOk () {
        this.$refs.table.refresh()
      },
      onSelectChange (selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      },
      getDipFrequency () {
        this.$nextTick(() => {
          getDipUploadFrequency().then(res => {
            this.times = res * 1000
            this.timerIntevalId = setInterval(() => {
              this.getNew(this.queryParam.channelId)
            }, this.times)
          })
        })
      },
      getNew (channelId) {
        if (channelId) {
          getNewOne({ channelId: channelId }).then(res => {
            if (res.success) {
              const data = res.data
              if (res.data === null) return
              this.dip = data.dip.split(',')
              if (this.changeChart) {
                if (this.chartData === [] || this.chartData.length === 0) {
                  return
                }
                const rowsa = this.chartData.rows
                const lastData = rowsa[rowsa.length - 1]
                if (lastData.createTime !== data.createTime) {
                  const newArray = []
                  for (let i = 1; i < rowsa.length; i++) {
                    newArray.push(rowsa[i])
                  }
                  newArray.push(data)
                  this.chartData.rows = newArray
                  this.updateChart()
                }
              }
            }
          })
        }
      },
      getStationTree () {
        treeList(this.queryParam).then(res => {
          this.treeLoading = false
          if (!res.success) {
            return
          }
          this.treeList = res.data
        })
      },
      onChange (value, selectedOptions) {
        this.queryParam.channelId = value[value.length - 1]
        this.getNew(this.queryParam.channelId)
        this.getDipFrequency()
        this.$refs.table.refresh()
      }
    },
    created () {
      this.getStationTree()
    },
    mounted () {
      // this.getTreeList()
    },

    destroyed () {
      if (this.timerIntevalId) {
        clearInterval(this.timerIntevalId)
      }
    }
  }
</script>

<style lang="less" scoped>
  .table-operator {
    margin-bottom: 18px;
  }

  button {
    margin-right: 8px;
  }
  .table-page-search-wrapper{
    padding-left: 10px;
  }
  .ant-cascader-picker {
    background: #104E5C;
    border: 1px solid #104E5C;
    color: #fff;
    .ant-cascader-menus-content .ant-cascader-menu{
      background: #104E5C;
    }
  }
  .ant-cascader-menus{
    background: #104E5C;
  }

  .dipPic {
    width: 304px;
    height: 279px;
    margin: 80px auto 0 20px;
    background-image: url(~@/assets/img/dippicbg.png);
    background-repeat: no-repeat;
    background-size: 100% 100%;
  }

  .dipClass {
    width: 304px;
    margin: 50px auto 0;
    color: #fff;
    padding-left: 56px;

    li {
      margin-bottom: 10px;
      list-style: none;

      .dipTip {
        display: inline-block;
        width: 120px;
        height: 22px;
        line-height: 22px;
        padding-left: 10px;
        background-image: url(~@/assets/img/dipbg.png);
        background-repeat: no-repeat;
        background-size: 100% 100%;
        font-size: 21px;
      }

      .dipNum {
        display: inline-block;
        margin-left: 10px;
        color: #19ECFF;
        font-size: 25px;
        width: 80px;
        text-align: right;
      }
    }
  }
</style>
